package com.example.demo;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    public UserService userService;


    @GetMapping
    public ApiResponse<List<User>> getAllUser(){

        return new ApiResponse<>(200,"请求成功！",userService.getAllUser());

    }

    @GetMapping("/{id}")
    public ApiResponse<User> getUserById(@PathVariable long id){

        User findUser = userService.getUserById(id);
        if(findUser==null)
            return new ApiResponse<>(400,"该用户不存在！",findUser);

        return new ApiResponse<>(200,"成功查找到该用户！",findUser);

    }

    @PostMapping
    public ApiResponse<Boolean> createUser(@RequestBody User user){

        if(!userService.createUser(user))
            return new ApiResponse<>(400,"该用户已存在！",false);

        return new ApiResponse<>(200,"注册成功！",true);


    }

    @PutMapping
    public ApiResponse<Boolean> updateUser(@RequestBody User user){

        if(!userService.updateUser(user))
            return new ApiResponse<>(400,"该用户不存在！",false);

        return new ApiResponse<>(200,"用户信息更新成功！",true);


    }

    @DeleteMapping("/{id}")
    public ApiResponse<Boolean> deleteUser(@PathVariable long id){

        if(!userService.deleteUser(id))
            return new ApiResponse<>(400,"删除失败！未查询到该用户！",false);

            return new ApiResponse<>(200,"成功注销！",true);

    }
}
